const FormData = require("form-data");
const axios = require("axios").default.create({
  headers: {
    "user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.34 (KHTML, like Gecko) Chrome/62.0.3325.180 Safari/537.35 OPR/52.0.2871.41"
  }
});
const fs = require("fs");
const CommonAxerrHG = require("./CommonAxerrHandlerGenerator").CommonAxerrHandlerGen;
const Toolbox = require("./Toolbox");
const util = require("util");
const path = require("path");
const fbase64 = require("file-base64");



const UPLOAD_URL = "http://upload.58cdn.com.cn/json";


/**
 * @returns {Promise<{ok:Boolean,msg:String,data:{link:String}}>}
 * @param {String} file_path 
 */
function uploadImage(file_path) {
  return new Promise(resolve => {
    fbase64.encode(file_path, (error, b64String) => {
      if (error) {
        return CommonAxerrHG(resolve)(`failed to base64fy file:${error}`);
      }
      let sent_data = {
        "Pic-Size": "0*0",
        "Pic-Encoding": "base64",
        "Pic-Path": "/nowater/webim/",
        "Pic-Data": b64String
      };
      axios.post(UPLOAD_URL, sent_data, {
        headers: {

        },
        maxContentLength: Number.MAX_SAFE_INTEGER
      }).then(axresp => {
        // debugger
        if (axresp.data && util.isString(axresp.data)) {
          return resolve({
            data: {
              link: `https://pic1.58cdn.com.cn/nowater/webim/big/${axresp.data}`
            },
            msg: "ok",
            ok: true
          })
        }
        throw new Error(`no sanity axresp:${util.inspect(axresp.data)}`)
      }).catch(axerr => {
        CommonAxerrHG(resolve)(axerr);
      });
    })


  })
}




module.exports = {
  uploadImage
}